package com.woquyin.controller.api;

import java.util.HashMap;
import java.util.Random;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;
import com.woquyin.common.Constance;
import com.woquyin.interceptor.ParamInterceptor;
import com.woquyin.utils.CommonUtil;
import com.woquyin.vo.ReturnData;

@Clear
public class UtilsController extends Controller {

	/**
	 * 注册短信验证码
	 */
	public void getValidateCode() {
		ReturnData<String> resp = new ReturnData<String>();
		// TODO 需要调用短信接口下发短信SMS_54795022
		String jsonString = getAttrForStr(ParamInterceptor.REQUEST_JSON);
		HashMap<String,String> data = FastJson.getJson().parse(jsonString, HashMap.class);
		String phone = data.get("phone");
		// String company = "我要去印网";
		// String code = generateCode();
		// String formatStr = "{\"code\":\"%s\",\"product\":\"%s\"}";
		// String smsParams = String.format(formatStr, code, company);
		// String smsTempletCode = "SMS_60745184";
		// AlibabaAliqinFcSmsNumSendResponse rsp =
		// SMSUtils.sendSmsReq(smsParams, smsTempletCode, phone);
		// if (rsp != null && rsp.isSuccess()) {
		// resp.setMsg("发送成功，请注意查看");
		// setSessionAttr(phone, code);
		// } else {
		// resp.setCode(ApiResult.APP_ERROR);
		// resp.setMsg("获取验证码过于频繁，请稍后。");
		// }
		resp.setMsg("发送成功，请注意查看");
		CommonUtil.putValidateCode(phone,"1234");
		renderJson(resp);
	}

	/**
	 * 验证验证码
	 */
	public void checkValidateCode() {
		ReturnData<String> resp = new ReturnData<String>();
		String jsonString = HttpKit.readData(getRequest());
		HashMap<String,String> data = FastJson.getJson().parse(jsonString, HashMap.class);
		String phone = data.get("phone");
		String code = data.get("validateCode");
		String key = data.get("key");
		Object objs = getSessionAttr(phone + key);
		if (objs != null && String.valueOf(objs).equals(code)) {
			resp.setMsg("验证码正确");
		} else {
			resp.setCode(Constance.WholeStateCodeEnum.OTHER_ERROR.getCode());
			resp.setMsg("验证码不正确");
		}
		renderJson(resp);

	}

	/**
	 *
	 * @return
	 */
	private String generateCode() {
		StringBuilder code = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			code.append(random.nextInt(9));
		}
		return code.toString();
	}

}
